package com.example.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.database.AccountBean;
import com.example.myapplication.database.DBManager;
import com.example.myapplication.ui.activity.MonthChartActivity;
import com.example.myapplication.ui.activity.RecordActivity;
import com.example.myapplication.ui.activity.SearchActivity;
import com.example.myapplication.ui.adapter.AccountAdapter;
import com.example.myapplication.util.FloatUtil;
import com.example.myapplication.view.BudgetDialog;
import com.example.myapplication.view.MoreDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private RelativeLayout mainRlTop;
    private ImageView mainIvSearch;
    private ListView main_lv;
    private ImageButton mainBtnMore;
    private ImageButton mainBtnEdit;
    List<AccountBean> mDatas;
    AccountAdapter adapter;
    int year, month, day;
    //头布局相关控件
    View headerView;
    TextView topOutTv,topInTv,topbudgetTv,topConTV;
    ImageView topshowIv;
    SharedPreferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        preferences = getSharedPreferences("budget", Context.MODE_PRIVATE);
        initView();
        initTime();
        //添加ListView的头布局
        addLVHeaderView();

        mDatas = new ArrayList<>();
        adapter = new AccountAdapter(this, mDatas);
        main_lv.setAdapter(adapter);
    }

    private void addLVHeaderView() {
        //将布局转为View对象
        headerView=getLayoutInflater().inflate(R.layout.item_mainlv_top,null);
        main_lv.addHeaderView(headerView);
        //查找头布局可用控件
        topOutTv=headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv=headerView.findViewById(R.id.item_mainlv_top_tv_in);
        topbudgetTv=headerView.findViewById(R.id.item_mainlv_top_tv_budget);
        topConTV=headerView.findViewById(R.id.item_mainlv_top_tv_day);
        topshowIv=headerView.findViewById(R.id.item_mainlv_top_iv_hide);

        headerView.setOnClickListener(this);
        topbudgetTv.setOnClickListener(this);
        topshowIv.setOnClickListener(this);
    }

    /**
     * 获取今日具体时间
     */
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
        setTopTvShow();
    }

    /**
     * 设置头布局当中文本内容的显示
     */
    private void setTopTvShow() {
        //获取今日支出和收入总金额,显示在view当中
        float incomsumoneDay = DBManager.getSumAccountOneDay(year, month, day, 1);
        float outcomesumOneDay = DBManager.getSumAccountOneDay(year, month, day, 0);
        String infoOneDay="今日支出￥"+outcomesumOneDay+"收入 ￥"+incomsumoneDay;
        topConTV.setText(infoOneDay);
        //获取本月收入和支出总金额
        float incomesumOneMonth = DBManager.getSumAccountOneMonth(year, month, 1);
        float outcomesumOneMonth = DBManager.getSumAccountOneMonth(year, month, 0);
        topInTv.setText("￥"+incomesumOneMonth);
        topOutTv.setText("￥"+outcomesumOneMonth);
        float bmoney = preferences.getFloat("bmoney", 0);
        if(bmoney==0){
            topbudgetTv.setText("￥ 0");
        }else{
            float syMoney = FloatUtil.sub(bmoney,outcomesumOneMonth);
            topbudgetTv.setText("￥"+syMoney);
        }
    }

    private void loadData() {
        List<AccountBean> accountListoneDayFromAccount = DBManager.getAccountListOneDay(year, month, day);
        mDatas.clear();
        mDatas.addAll(accountListoneDayFromAccount);
        adapter.notifyDataSetChanged();
    }

    /**
     * 主页面的点击事件
     * @param view
     */
    public void onMainClick(View view) {
        switch (view.getId()) {
            case R.id.main_iv_search:
                Intent intent = new Intent(this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.main_btn_more:
                MoreDialog moreDialog = new MoreDialog(this);
                moreDialog.show();
                moreDialog.setDialogSize();
                break;
            case R.id.main_btn_edit:
                startActivity(new Intent(this, RecordActivity.class));//跳转界面
                break;
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mainRlTop = (RelativeLayout) findViewById(R.id.main_rl_top);
        mainIvSearch = (ImageView) findViewById(R.id.main_iv_search);
        mainBtnMore = (ImageButton) findViewById(R.id.main_btn_more);
        mainBtnEdit = (ImageButton) findViewById(R.id.main_btn_edit);
        main_lv = (ListView) findViewById(R.id.main_lv);
        setLVLongClickListener();

    }
    /**
     * 设置ListView的长按事件
     */

    private void setLVLongClickListener() {
    main_lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if (position==0){//点击了头布局
                return false;
            }
            int pos = position - 1;
            final AccountBean bean = mDatas.get(pos);
            final int ac_id = bean.getId();
            //弹出对话框，提示用户是否确定要删除
            setDelectItemDialog(bean, ac_id);
            return false;
        }
    });
    }

    /**
     * 弹出是删除某一条记录的对话框
     * @param bean 实体类
     * @param ac_id 数据库记录条数的主键id
     */
    private void setDelectItemDialog(AccountBean bean, int ac_id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("提示信息").setMessage("您确定要删除这条记录么?")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DBManager.deleteItemFromAccountById(ac_id);
                        mDatas.remove(bean);    //从集合当中移除对象
                        adapter.notifyDataSetChanged();//提示适配器更新
                        setTopTvShow();//改变头布局TextView显示的内容
                    }
                });
        builder.create().show();
    }

    /**
     * ListView头布局点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.item_mainlv_top_tv_budget:
                showBudgetDialog();
                break;
            case R.id.item_mainlv_top_iv_hide:
                //切换TextView明文与密文
                toggleshow();
                break;
        }
        if (v==headerView){
            Intent intent = new Intent(this, MonthChartActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 显示预算设置对话框
     */
    private void showBudgetDialog() {
        BudgetDialog budgetDialog = new BudgetDialog(this);
        budgetDialog.setDialogSize();
        budgetDialog.show();
        budgetDialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(float money) {
                // 将预算的金额使用共享参数进行临时存储
                SharedPreferences.Editor editor = preferences.edit();   //得到写入数据的editor对象
                editor.putFloat("bmoney",money);
                editor.commit();
                float outcomeOneMonth = DBManager.getSumAccountOneMonth(year, month, 0);
                money= FloatUtil.sub(money,outcomeOneMonth);  // 预算剩余钱数=预算金额-本月支出
                topbudgetTv.setText("￥"+money);
            }
        });
    }

    boolean isShow=true;
    /**
     * 点击头布局眼睛时，如果原来是明文，就加密，如果是密文，就显示出来
     */
    private void toggleshow() {
        if (isShow){
            PasswordTransformationMethod passwordMethod = PasswordTransformationMethod.getInstance();
            topInTv.setTransformationMethod(passwordMethod);//设置隐藏;
            topOutTv.setTransformationMethod(passwordMethod);//设置隐藏;
            topbudgetTv.setTransformationMethod(passwordMethod);//设置隐藏;
            topshowIv.setImageResource(R.mipmap.ih_hide);
            isShow=false;
        }else {
            HideReturnsTransformationMethod instance = HideReturnsTransformationMethod.getInstance();
            topInTv.setTransformationMethod(instance);//设置隐藏;
            topOutTv.setTransformationMethod(instance);//设置隐藏;
            topbudgetTv.setTransformationMethod(instance);//设置隐藏;
            topshowIv.setImageResource(R.mipmap.ih_show);
            isShow=true;
        }
    }
}